package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.context.BaseContext;
import com.ydd.dto.ArticlePageDTO;
import com.ydd.entity.YddArticle;
import com.ydd.exception.BaseException;
import com.ydd.mapper.ArticleMapper;
import com.ydd.result.PageResult;
import com.ydd.service.ArticleService;
import com.ydd.vo.YddArticleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    /**
     * 分页查询
     *
     * @param articlePageDTO
     * @return
     */
    @Override
    public PageResult list(ArticlePageDTO articlePageDTO) {
        if (Objects.isNull(articlePageDTO)) {
            throw new BaseException(MessageConstant.Parameter_Empty);
        }
        PageHelper.startPage(articlePageDTO.getPage(),articlePageDTO.getLimit());
        Page<YddArticleVO> page = articleMapper.list(articlePageDTO);
        Long totalPages = page.getTotal()/articlePageDTO.getLimit();
        int intTotalPages = totalPages.intValue();
        return new PageResult(page.getTotal(),articlePageDTO.getPage(),
                page.getResult(),articlePageDTO.getLimit(),intTotalPages+1);
    }

    /**
     * 根据id删除文章
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        if (Objects.isNull(id)) {
            throw new BaseException(MessageConstant.Parameter_Empty);
        }
        articleMapper.deleteById(id);
    }

    /**
     * 文章添加
     *
     * @param yddArticle
     */
    @Override
    public void add(YddArticle yddArticle) {
        if (Objects.isNull(yddArticle)) {
            throw new BaseException(MessageConstant.Parameter_Empty);
        }
        yddArticle.setUserId(Integer.parseInt((String) BaseContext.getCurrentId()));
        yddArticle.setDefaultData("1");
        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setStatus(2);
        articleMapper.add(yddArticle);
    }

    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @Override
    public YddArticle rowInfo(Integer id) {
        if (Objects.isNull(id)) {
            throw new BaseException(MessageConstant.Parameter_Empty);
        }
        YddArticle yddArticle = articleMapper.rowInfo(id);
        return yddArticle;
    }

    /**
     * 文章修改
     *
     * @param yddArticle
     */
    @Override
    public void update(YddArticle yddArticle) {
        if (Objects.isNull(yddArticle)) {
            throw new BaseException(MessageConstant.Parameter_Empty);
        }
        articleMapper.updateById(yddArticle);
    }
}
